package com.xxwy.ddu.security.app.controller;

import com.xxwy.ddu.security.app.social.signup.AppSignUpUtils;
import com.xxwy.ddu.security.code.authentication.qq.bean.SocialUserInfo;
import com.xxwy.ddu.security.code.properties.SecurityProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * @author xxwy
 * on 2018/9/20 0020
 */
@Slf4j
@RestController
public class AppSecurityController {
    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    @Autowired
    private AppSignUpUtils appSingUpUtils;

    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 需要注册时跳到这里，返回401和用户信息给前端
     *
     * @param request
     * @return
     */
    @GetMapping("/social/signUp")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public SocialUserInfo getSocialUserInfo(HttpServletRequest request) {
        SocialUserInfo userInfo = new SocialUserInfo();
        Connection<?> connection = providerSignInUtils
                .getConnectionFromSession(new ServletWebRequest(request));
        userInfo.setProviderId(connection.getKey().getProviderId());
        userInfo.setProviderUserId(connection.getKey().getProviderUserId());
        userInfo.setNickname(connection.getDisplayName());
        userInfo.setHeadimg(connection.getImageUrl());
//        保存到redis
        appSingUpUtils.saveConnectionData(new ServletWebRequest(request),
                connection.createData());
        return userInfo;
    }

    /**
     * 获取用户信息
     *
     */
    @GetMapping("/user/info")
    public ResponseEntity<Claims> userInfo(HttpServletRequest request) throws UnsupportedEncodingException {
        String authorization = request.getHeader("Authorization");
        if (!StringUtils.isBlank(authorization)) {
            String jwtSigningKey = securityProperties.getOauth2().getJwtSigningKey();
            String token = StringUtils.substringAfter(authorization, "bearer ");
            log.info("jwt token", token);
            // 生成的时候使用的是 org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter
            // 源码里面把signingkey变成utf8了
            // JwtAccessTokenConverter类，解析出来是一个map
            // 所以这个自带的JwtAccessTokenConverter对象也是可以直接用来解析的
            byte[] bytes = jwtSigningKey.getBytes("utf-8");
            Claims body = Jwts.parser().setSigningKey(bytes).parseClaimsJws(token).getBody();
            return ResponseEntity.ok(body);
        } else {
            return null;
        }

    }
}
